# -*- coding: utf-8 -*-

"""
 (c) 2023 - Copyright CTyunOS Inc

 Authors:
   youyifeng <youyf2@chinatelecom.cn>

"""

import logging
from optparse import OptionParser

from cve_ease import activate_session
from cve_ease.helper import parseRPM

logger = logging.getLogger('cve-ease')


def get_usage_str(usage):
    return usage + "\n(Specify the --help global option for a list of other help options)"


def handle_rpm(gconfig, db_session, args):
    """[basic] Local rpm info tool"""
    usage = "usage: %prog rpm <options>"
    parser = OptionParser(usage=get_usage_str(usage))

    parser.add_option('-l', '--list', dest='list', action='store_true', default=False,
                      help='list all rpm info')
    parser.add_option('-v', '--verbose', dest='verbose', action='store_true', default=False,
                      help='show verbose output')

    (options, args) = parser.parse_args(args)

    session = activate_session(db_session, gconfig)
    if gconfig.debug:
        print(" * active sql session")

    if options.list:
        try:
            import rpm
        except Exception as e:
            print("import rpm failed!", str(e))
            exit(1)
        ts = rpm.TransactionSet()
        rpm_hdr_iter = ts.dbMatch()
        print(
            "%-30s %-20s %-5s  %-20s %-15s %s(%s)" % ("NAME", "VERSION", "EPOCH", "RELEASE", "ARCH", "SOURCE", "SNAME")
        )
        for rpm_hdr in rpm_hdr_iter:
            srpm = rpm_hdr[rpm.RPMTAG_SOURCERPM]
            name, ver, rel, epoch, arch = parseRPM(srpm)
            print("%-30s %-20s %-5s %-20s %-15s %s(%s)" % (
                rpm_hdr[rpm.RPMTAG_NAME],
                rpm_hdr[rpm.RPMTAG_VERSION],
                rpm_hdr[rpm.RPMTAG_EPOCH] or '0',
                rpm_hdr[rpm.RPMTAG_RELEASE],
                rpm_hdr[rpm.RPMTAG_ARCH],
                srpm,
                name
            ))
    else:
        parser.print_help()
